package org.belkodevelop.user.dao;

import java.util.List;
import org.belkodevelop.user.domain.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Repository;

@Repository
public class UserDAOImpl implements UserDAO {
    
    @Autowired
    private SessionFactory sessionFactory;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void addUser(User user) {
        user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
        sessionFactory.getCurrentSession().save(user);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> listUsers() {
        return sessionFactory.getCurrentSession().createQuery("from users").list();
    }

    @Override
    public void removeUser(long id) {
        /*User user = (User) sessionFactory.getCurrentSession().get(User.class, id);
        if (null != user) {
            sessionFactory.getCurrentSession().delete(user);
        }*/
        Query query = sessionFactory.getCurrentSession().
                createQuery("delete from User where id = :id");
        query.setParameter("id", id);
        query.executeUpdate();
    }

    @Override
    public User getUser(String login) {
        return (User)sessionFactory.getCurrentSession().
                createCriteria(User.class).add(Restrictions.eq("login", login)).uniqueResult();
    }
    
    @Override
    public User getUserByEmail(String email) {
        return (User)sessionFactory.getCurrentSession().
                createCriteria(User.class).add(Restrictions.eq("email", email)).uniqueResult();
    }
    
    @Override
    public void saveUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public User getUser(long id) {
        return (User) sessionFactory.getCurrentSession().get(User.class, id);
    }
    
}